// local-pve.js - 本地PVE对决模式游戏逻辑

class LocalPVEGame {
    constructor() {
        this.canvas = document.getElementById('gameCanvas');
        this.ctx = this.canvas.getContext('2d');
        
        // 游戏配置
        this.gridSize = 20;
        this.canvasWidth = this.canvas.width;
        this.canvasHeight = this.canvas.height;
        this.gridWidth = Math.floor(this.canvasWidth / this.gridSize);
        this.gridHeight = Math.floor(this.canvasHeight / this.gridSize);
        
        // 游戏状态
        this.gameRunning = false;
        this.gamePaused = false;
        this.gameOver = false;
        this.gameStarted = false;
        this.isChallengeMode = false; // 是否为挑战模式
        
        // 计时器
        this.totalTime = 120; // 2分钟（普通模式）
        this.challengeTotalTime = 180; // 3分钟（挑战模式）
        this.remainingTime = this.totalTime;
        this.timerInterval = null;
        
        // 玩家蛇
        this.playerSnake = {
            body: [],
            direction: 'right',
            color: '#4CAF50',
            headColor: '#66BB6A',
            score: 0,
            initialLength: 3 // 普通模式初始长度
        };
        
        // AI蛇
        this.aiSnake = {
            body: [],
            direction: 'left',
            color: '#FF9800',
            headColor: '#FFB74D',
            score: 0,
            isAlive: true
        };
        
        // 挑战模式第二条AI蛇
        this.aiSnake2 = {
            body: [],
            direction: 'up',
            color: '#E91E63',
            headColor: '#EC407A',
            score: 0,
            isAlive: true
        };
        
        // AI实例
        this.ai = null;
        this.ai2 = null; // 挑战模式第二条AI
        
        // 食物
        this.food = null;
        this.food2 = null; // 第二个普通红色食物
        this.goldenFood = null;
        this.goldenFoodTimer = 0;
        this.goldenFoodInterval = 10; // 每10秒出现一次金色食物
        
        // 移动食物（中等难度特有）
        this.movingFood = null;
        this.movingFoodTimer = 0;
        this.movingFoodInterval = 30; // 每30秒出现一次移动食物
        this.movingFoodDirection = 'right'; // 初始移动方向
        
        // 初始化
        this.init();
        this.setupEventListeners();
    }
    
    init() {
        // 初始化AI
        this.ai = new LocalPVEAI(this);
        
        this.resetGame();
        this.showStartScreen();
        this.setupModeSelection();
        
        // 设置默认难度为中等，并确保极限模式选择正确
        this.setDefaultDifficulty();
    }
    
    setDefaultDifficulty() {
        // 设置默认难度为中等，并确保UI状态正确
        const mediumOption = document.querySelector('[data-difficulty="medium"]');
        if (mediumOption) {
            mediumOption.classList.add('active');
            this.isChallengeMode = false;
            if (this.ai) {
                this.ai.setDifficulty('medium');
            }
        }
    }
    
    setupModeSelection() {
        const normalModeRadio = document.getElementById('mode-normal');
        const challengeModeRadio = document.getElementById('mode-challenge');
        const normalModeLabel = document.querySelector('label[for="mode-normal"]');
        const challengeModeLabel = document.querySelector('label[for="mode-challenge"]');
        
        if (normalModeLabel && challengeModeLabel) {
            normalModeLabel.addEventListener('click', () => {
                this.isChallengeMode = false;
                normalModeLabel.classList.add('active');
                challengeModeLabel.classList.remove('active');
                this.updateModeDescription();
            });
            
            challengeModeLabel.addEventListener('click', () => {
                this.isChallengeMode = true;
                challengeModeLabel.classList.add('active');
                normalModeLabel.classList.remove('active');
                this.updateModeDescription();
            });
        }
    }
    
    updateModeDescription() {
        const modeDescription = document.getElementById('modeDescription');
        if (modeDescription) {
            if (this.isChallengeMode) {
                modeDescription.innerHTML = `
                    <h5>挑战模式特性：</h5>
                    <ul>
                        <li>AI将同时控制两条蛇（出生点分开）</li>
                        <li>AI蛇之间不会相互撞死，但会避免碰撞和抢食</li>
                        <li>玩家初始长度+5（总共8格）</li>
                        <li>击败AI可获得其长度加成</li>
                        <li>游戏时间3分钟</li>
                        <li>AI两条蛇得分分别计算</li>
                    </ul>
                `;
            } else {
                modeDescription.innerHTML = `
                    <h5>普通模式特性：</h5>
                    <ul>
                        <li>玩家与单个AI对战</li>
                        <li>游戏时间2分钟</li>
                        <li>标准贪吃蛇规则</li>
                    </ul>
                `;
            }
        }
    }
    
    updateDifficultyInfo(difficulty) {
        const difficultyTitle = document.getElementById('difficulty-title');
        const difficultyDescription = document.getElementById('difficulty-description');
        const difficultyInfo = document.querySelector('.difficulty-info');
        
        if (difficultyTitle && difficultyDescription && difficultyInfo) {
            // 移除所有难度相关的类
            difficultyInfo.classList.remove('easy', 'medium', 'hard', 'extreme');
            
            // 添加当前难度对应的类
            difficultyInfo.classList.add(difficulty);
            
            // 根据难度更新标题和描述
            switch(difficulty) {
                case 'easy':
                    difficultyTitle.textContent = '简单模式特性';
                    difficultyDescription.innerHTML = `
                        <ul>
                            <li>AI移动速度较慢</li>
                            <li>游戏时间2分钟</li>
                            <li>标准贪吃蛇规则</li>
                            <li>适合新手玩家练习</li>
                        </ul>
                    `;
                    break;
                case 'medium':
                    difficultyTitle.textContent = '中等模式特性';
                    difficultyDescription.innerHTML = `
                        <ul>
                            <li>AI移动速度中等</li>
                            <li>游戏时间2分钟</li>
                            <li>每30秒出现移动食物</li>
                            <li>AI会主动寻找食物</li>
                        </ul>
                    `;
                    break;
                case 'hard':
                    difficultyTitle.textContent = '困难模式特性';
                    difficultyDescription.innerHTML = `
                        <ul>
                            <li>AI移动速度较快</li>
                            <li>游戏时间2分钟</li>
                            <li>AI具有更强的路径规划能力</li>
                            <li>AI会主动拦截玩家</li>
                        </ul>
                    `;
                    break;
                case 'extreme':
                    difficultyTitle.textContent = '极限挑战特性';
                    difficultyDescription.innerHTML = `
                        <ul>
                            <li>AI将同时控制两条蛇</li>
                            <li>玩家初始长度+5（总共8格）</li>
                            <li>游戏时间3分钟</li>
                            <li>击败AI可获得其长度加成</li>
                            <li>AI蛇之间不会相互撞死</li>
                        </ul>
                    `;
                    break;
                default:
                    difficultyTitle.textContent = '难度特性';
                    difficultyDescription.innerHTML = `
                        <ul>
                            <li>请选择难度查看详细特性</li>
                        </ul>
                    `;
            }
        }
    }
    
    setupEventListeners() {
        // 键盘控制（支持方向键和WASD键）
        document.addEventListener('keydown', (e) => {
            if (!this.gameRunning || this.gamePaused) return;
            
            switch(e.key) {
                case 'ArrowUp':
                case 'w':
                case 'W':
                    if (this.playerSnake.direction !== 'down') {
                        this.playerSnake.direction = 'up';
                    }
                    break;
                case 'ArrowDown':
                case 's':
                case 'S':
                    if (this.playerSnake.direction !== 'up') {
                        this.playerSnake.direction = 'down';
                    }
                    break;
                case 'ArrowLeft':
                case 'a':
                case 'A':
                    if (this.playerSnake.direction !== 'right') {
                        this.playerSnake.direction = 'left';
                    }
                    break;
                case 'ArrowRight':
                case 'd':
                case 'D':
                    if (this.playerSnake.direction !== 'left') {
                        this.playerSnake.direction = 'right';
                    }
                    break;
                case ' ':
                    this.togglePause();
                    break;
            }
        });
        
        // 按钮事件
        // 难度选择事件
        document.querySelectorAll('.difficulty-option').forEach(option => {
            option.addEventListener('click', () => {
                // 移除所有active类
                document.querySelectorAll('.difficulty-option').forEach(opt => {
                    opt.classList.remove('active');
                });
                
                // 添加active类到当前选项
                option.classList.add('active');
                
                // 更新AI难度
                const difficulty = option.getAttribute('data-difficulty');
                if (this.ai) {
                    this.ai.setDifficulty(difficulty);
                }
                
                // 设置极限挑战模式
                this.isChallengeMode = difficulty === 'extreme';
                // 直接设置第二条AI蛇的存活状态，不依赖ai2实例
                this.aiSnake2.isAlive = this.isChallengeMode;
                
                // 更新难度说明栏
                this.updateDifficultyInfo(difficulty);
            });
        });
        
        document.getElementById('startBtn').addEventListener('click', () => {
            this.startGame();
        });
        
        document.getElementById('pauseBtn').addEventListener('click', () => {
            this.togglePause();
        });
        
        document.getElementById('restartBtn').addEventListener('click', () => {
            this.restartGame();
        });
        
        document.getElementById('backBtn').addEventListener('click', () => {
            window.location.href = 'game-home.html';
        });
        
        document.getElementById('playAgainBtn').addEventListener('click', () => {
            this.restartGame();
        });
        
        document.getElementById('backToMenuBtn').addEventListener('click', () => {
            window.location.href = 'game-home.html';
        });
    }
    
    showStartScreen() {
        const overlay = document.getElementById('gameOverlay');
        const title = document.getElementById('overlayTitle');
        const message = document.getElementById('overlayMessage');
        const startBtn = document.getElementById('startBtn');
        
        overlay.classList.remove('hidden');
        title.textContent = '本地PVE对决';
        message.textContent = '选择难度并使用方向键或WASD键控制蛇的移动。每10秒会出现金色食物（30分）！';
        startBtn.textContent = '开始游戏';
        
        // 设置默认难度
        if (this.ai) {
            this.ai.setDifficulty('medium');
        }
    }
    
    startGame() {
        this.gameRunning = true;
        this.gameStarted = true;
        this.gamePaused = false;
        this.gameOver = false;
        
        document.getElementById('gameOverlay').classList.add('hidden');
        
        // 挑战模式下初始化第二条AI
        if (this.isChallengeMode) {
            this.ai2 = new LocalPVEAI(this, true); // true表示这是第二条AI蛇的AI实例
            // 设置第二条AI的难度为极限挑战
            this.ai2.setDifficulty('extreme');
        }
        
        // 开始计时器
        this.startTimer();
        
        // 开始游戏循环
        this.gameLoop();
    }
    
    startTimer() {
        this.remainingTime = this.isChallengeMode ? this.challengeTotalTime : this.totalTime;
        this.updateTimerDisplay();
        
        this.timerInterval = setInterval(() => {
            if (this.gameRunning && !this.gamePaused && !this.gameOver) {
                this.remainingTime--;
                this.updateTimerDisplay();
                
                if (this.remainingTime <= 0) {
                    this.endGame('时间到！');
                }
            }
        }, 1000);
    }
    
    updateTimerDisplay() {
        const minutes = Math.floor(this.remainingTime / 60);
        const seconds = this.remainingTime % 60;
        document.getElementById('timer').textContent = 
            `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
    }
    
    resetGame() {
        // 重置玩家蛇
        const playerInitialLength = this.isChallengeMode ? 8 : 3; // 挑战模式初始长度+5
        this.playerSnake.body = [];
        // 修正蛇身初始化：蛇头在最后位置，蛇身向前延伸
        for (let i = playerInitialLength - 1; i >= 0; i--) {
            this.playerSnake.body.push({ x: 3 + i, y: Math.floor(this.gridHeight / 2) });
        }
        this.playerSnake.direction = 'right';
        this.playerSnake.score = 0;
        this.playerSnake.initialLength = playerInitialLength;
        
        // 重置AI蛇
        this.aiSnake.body = [
            {x: this.gridWidth - 4, y: Math.floor(this.gridHeight / 2)},
            {x: this.gridWidth - 3, y: Math.floor(this.gridHeight / 2)},
            {x: this.gridWidth - 2, y: Math.floor(this.gridHeight / 2)}
        ];
        this.aiSnake.direction = 'left';
        this.aiSnake.score = 0;
        this.aiSnake.isAlive = true;
        
        // 重置挑战模式第二条AI蛇
        this.aiSnake2.body = [
            {x: this.gridWidth - 4, y: Math.floor(this.gridHeight / 2) - 3},
            {x: this.gridWidth - 3, y: Math.floor(this.gridHeight / 2) - 3},
            {x: this.gridWidth - 2, y: Math.floor(this.gridHeight / 2) - 3}
        ];
        this.aiSnake2.direction = 'up';
        this.aiSnake2.score = 0;
        this.aiSnake2.isAlive = this.isChallengeMode; // 仅在挑战模式下存活
        
        // 生成食物
        this.generateFood();
        this.food2 = null; // 第二个食物会在generateFood中生成
        this.goldenFood = null;
        this.goldenFoodTimer = 0;
        
        // 重置移动食物
        this.movingFood = null;
        this.movingFoodTimer = 0;
        this.movingFoodDirection = 'right';
        
        // 重置计时器
        this.remainingTime = this.isChallengeMode ? this.challengeTotalTime : this.totalTime;
        
        // 更新分数显示
        this.updateScoreDisplay();
        this.updateAIInfoDisplay();
    }
    
    generateFood() {
        // 如果第一个食物不存在，生成第一个普通红色食物
        if (!this.food) {
            let foodPosition1;
            let validPosition1 = false;
            
            while (!validPosition1) {
                foodPosition1 = {
                    x: Math.floor(Math.random() * (this.gridWidth - 4)) + 2,
                    y: Math.floor(Math.random() * (this.gridHeight - 4)) + 2
                };
                
                // 检查食物是否与蛇身重叠
                validPosition1 = true;
                for (let segment of this.playerSnake.body) {
                    if (segment.x === foodPosition1.x && segment.y === foodPosition1.y) {
                        validPosition1 = false;
                        break;
                    }
                }
                for (let segment of this.aiSnake.body) {
                    if (segment.x === foodPosition1.x && segment.y === foodPosition1.y) {
                        validPosition1 = false;
                        break;
                    }
                }
            }
            
            this.food = foodPosition1;
        }
        
        // 如果第二个食物不存在，生成第二个普通红色食物
        if (!this.food2) {
            let foodPosition2;
            let validPosition2 = false;
            
            while (!validPosition2) {
                foodPosition2 = {
                    x: Math.floor(Math.random() * (this.gridWidth - 4)) + 2,
                    y: Math.floor(Math.random() * (this.gridHeight - 4)) + 2
                };
                
                // 检查食物是否与蛇身或第一个食物重叠
                validPosition2 = true;
                for (let segment of this.playerSnake.body) {
                    if (segment.x === foodPosition2.x && segment.y === foodPosition2.y) {
                        validPosition2 = false;
                        break;
                    }
                }
                for (let segment of this.aiSnake.body) {
                    if (segment.x === foodPosition2.x && segment.y === foodPosition2.y) {
                        validPosition2 = false;
                        break;
                    }
                }
                // 检查是否与第一个食物重叠
                if (this.food && this.food.x === foodPosition2.x && this.food.y === foodPosition2.y) {
                    validPosition2 = false;
                }
            }
            
            this.food2 = foodPosition2;
        }
    }
    
    generateGoldenFood() {
        let foodPosition;
        let validPosition = false;
        
        while (!validPosition) {
            foodPosition = {
                x: Math.floor(Math.random() * (this.gridWidth - 4)) + 2,
                y: Math.floor(Math.random() * (this.gridHeight - 4)) + 2
            };
            
            // 检查金色食物是否与蛇身或普通食物重叠
            validPosition = true;
            for (let segment of this.playerSnake.body) {
                if (segment.x === foodPosition.x && segment.y === foodPosition.y) {
                    validPosition = false;
                    break;
                }
            }
            for (let segment of this.aiSnake.body) {
                if (segment.x === foodPosition.x && segment.y === foodPosition.y) {
                    validPosition = false;
                    break;
                }
            }
            
            // 检查是否与普通食物重叠
            if (this.food && this.food.x === foodPosition.x && this.food.y === foodPosition.y) {
                validPosition = false;
            }
        }
        
        this.goldenFood = foodPosition;
    }
    
    // 生成移动食物
    generateMovingFood() {
        let foodPosition;
        let validPosition = false;
        
        while (!validPosition) {
            foodPosition = {
                x: Math.floor(Math.random() * (this.gridWidth - 4)) + 2,
                y: Math.floor(Math.random() * (this.gridHeight - 4)) + 2
            };
            
            // 检查移动食物是否与蛇身或普通食物重叠
            validPosition = true;
            for (let segment of this.playerSnake.body) {
                if (segment.x === foodPosition.x && segment.y === foodPosition.y) {
                    validPosition = false;
                    break;
                }
            }
            for (let segment of this.aiSnake.body) {
                if (segment.x === foodPosition.x && segment.y === foodPosition.y) {
                    validPosition = false;
                    break;
                }
            }
            
            // 检查是否与普通食物重叠
            if (this.food && this.food.x === foodPosition.x && this.food.y === foodPosition.y) {
                validPosition = false;
            }
            
            // 检查是否与金色食物重叠
            if (this.goldenFood && this.goldenFood.x === foodPosition.x && this.goldenFood.y === foodPosition.y) {
                validPosition = false;
            }
        }
        
        this.movingFood = foodPosition;
        // 随机选择初始移动方向
        const directions = ['up', 'down', 'left', 'right'];
        this.movingFoodDirection = directions[Math.floor(Math.random() * directions.length)];
    }
    
    // 移动食物的逻辑（类似蛇头移动，但速度更慢）
    moveMovingFood() {
        if (!this.movingFood) return;
        
        const newPos = {...this.movingFood};
        
        // 根据当前方向移动（类似蛇头移动）
        switch(this.movingFoodDirection) {
            case 'up': newPos.y--; break;
            case 'down': newPos.y++; break;
            case 'left': newPos.x--; break;
            case 'right': newPos.x++; break;
        }
        
        // 检查边界碰撞，如果碰撞则改变方向
        if (newPos.x < 0 || newPos.x >= this.gridWidth || 
            newPos.y < 0 || newPos.y >= this.gridHeight) {
            // 碰到边界，反弹（改变方向）
            switch(this.movingFoodDirection) {
                case 'up': this.movingFoodDirection = 'down'; break;
                case 'down': this.movingFoodDirection = 'up'; break;
                case 'left': this.movingFoodDirection = 'right'; break;
                case 'right': this.movingFoodDirection = 'left'; break;
            }
            return;
        }
        
        // 检查是否与蛇身重叠，如果重叠则改变方向
        let validPosition = true;
        for (let segment of this.playerSnake.body) {
            if (segment.x === newPos.x && segment.y === newPos.y) {
                validPosition = false;
                break;
            }
        }
        for (let segment of this.aiSnake.body) {
            if (segment.x === newPos.x && segment.y === newPos.y) {
                validPosition = false;
                break;
            }
        }
        
        if (!validPosition) {
            // 碰到蛇身，随机改变方向
            const directions = ['up', 'down', 'left', 'right'];
            this.movingFoodDirection = directions[Math.floor(Math.random() * directions.length)];
            return;
        }
        
        // 检查是否与普通食物重叠
        if (this.food && this.food.x === newPos.x && this.food.y === newPos.y) {
            // 与普通食物重叠，改变方向
            const directions = ['up', 'down', 'left', 'right'];
            this.movingFoodDirection = directions[Math.floor(Math.random() * directions.length)];
            return;
        }
        
        // 检查是否与金色食物重叠
        if (this.goldenFood && this.goldenFood.x === newPos.x && this.goldenFood.y === newPos.y) {
            // 与金色食物重叠，改变方向
            const directions = ['up', 'down', 'left', 'right'];
            this.movingFoodDirection = directions[Math.floor(Math.random() * directions.length)];
            return;
        }
        
        // 如果位置有效，更新移动食物位置
        this.movingFood = newPos;
    }
    
    gameLoop() {
        if (!this.gameRunning || this.gamePaused || this.gameOver) return;
        
        // 更新游戏状态
        this.update();
        
        // 绘制游戏画面
        this.draw();
        
        // 检查游戏结束条件
        this.checkGameEnd();
        
        // 继续游戏循环
        setTimeout(() => this.gameLoop(), 100);
    }
    
    update() {
        this.moveSnake(this.playerSnake);
        this.moveAI();
        this.checkCollisions();
        this.checkFood();
        this.updateGoldenFood();
        
        // 更新移动食物计时器（仅在中等难度时生效）
        if (this.ai && this.ai.difficulty === 'medium') {
            this.movingFoodTimer++;
            if (this.movingFoodTimer >= 300) { // 每30秒生成移动食物（10帧/秒 * 30秒 = 300帧）
                this.generateMovingFood();
                this.movingFoodTimer = 0;
            }
            
            // 每4帧移动一次移动食物（2.5次/秒，比正常蛇慢）
            if (this.frameCount % 4 === 0 && this.movingFood) {
                this.moveMovingFood();
            }
        }
    }
    
    updateGoldenFood() {
        if (this.gameRunning && !this.gamePaused && !this.gameOver) {
            this.goldenFoodTimer++;
            
            // 每10秒生成金色食物（10帧/秒 * 10秒 = 100帧）
            if (this.goldenFoodTimer >= 100) {
                this.generateGoldenFood();
                this.goldenFoodTimer = 0;
            }
        }
    }
    
    moveSnake(snake) {
        // 移动蛇身
        const head = {...snake.body[0]};
        
        switch(snake.direction) {
            case 'up': head.y--; break;
            case 'down': head.y++; break;
            case 'left': head.x--; break;
            case 'right': head.x++; break;
        }
        
        snake.body.unshift(head);
        snake.body.pop();
    }
    
    moveAI() {
        // 使用新的AI类进行移动决策
        if (this.ai && this.aiSnake.isAlive) {
            this.ai.moveAI();
            this.moveSnake(this.aiSnake);
        }
        
        // 挑战模式下移动第二条AI蛇
        if (this.isChallengeMode && this.ai2 && this.aiSnake2.isAlive) {
            this.ai2.moveAI();
            this.moveSnake(this.aiSnake2);
        }
    }
    

    
    checkCollisions() {
        const playerHead = this.playerSnake.body[0];
        const aiHead = this.aiSnake.body[0];
        const aiHead2 = this.aiSnake2.body[0];
        
        // 检查边界碰撞
        if (playerHead.x < 0 || playerHead.x >= this.gridWidth || 
            playerHead.y < 0 || playerHead.y >= this.gridHeight) {
            this.endGame('玩家撞墙！AI获胜！');
            return;
        }
        
        if (this.aiSnake.isAlive && (aiHead.x < 0 || aiHead.x >= this.gridWidth || 
            aiHead.y < 0 || aiHead.y >= this.gridHeight)) {
            this.killAISnake(this.aiSnake);
        }
        
        if (this.isChallengeMode && this.aiSnake2.isAlive && (aiHead2.x < 0 || aiHead2.x >= this.gridWidth || 
            aiHead2.y < 0 || aiHead2.y >= this.gridHeight)) {
            this.killAISnake(this.aiSnake2);
        }
        
        // 检查蛇头撞到任意蛇尾
        for (let i = 1; i < this.playerSnake.body.length; i++) {
            if (playerHead.x === this.playerSnake.body[i].x && playerHead.y === this.playerSnake.body[i].y) {
                this.endGame('玩家撞到自己！AI获胜！');
                return;
            }
        }
        
        if (this.aiSnake.isAlive) {
            for (let i = 1; i < this.aiSnake.body.length; i++) {
                if (aiHead.x === this.aiSnake.body[i].x && aiHead.y === this.aiSnake.body[i].y) {
                    this.killAISnake(this.aiSnake);
                    break;
                }
            }
        }
        
        if (this.isChallengeMode && this.aiSnake2.isAlive) {
            for (let i = 1; i < this.aiSnake2.body.length; i++) {
                if (aiHead2.x === this.aiSnake2.body[i].x && aiHead2.y === this.aiSnake2.body[i].y) {
                    this.killAISnake(this.aiSnake2);
                    break;
                }
            }
        }
        
        // 检查蛇头相撞
        if (this.aiSnake.isAlive && playerHead.x === aiHead.x && playerHead.y === aiHead.y) {
            this.killAISnake(this.aiSnake);
        }
        
        if (this.isChallengeMode && this.aiSnake2.isAlive && playerHead.x === aiHead2.x && playerHead.y === aiHead2.y) {
            this.killAISnake(this.aiSnake2);
        }
        
        // 检查玩家蛇头撞到AI蛇身
        if (this.aiSnake.isAlive) {
            for (let i = 1; i < this.aiSnake.body.length; i++) {
                if (playerHead.x === this.aiSnake.body[i].x && playerHead.y === this.aiSnake.body[i].y) {
                    this.killAISnake(this.aiSnake);
                    break;
                }
            }
        }
        
        if (this.isChallengeMode && this.aiSnake2.isAlive) {
            for (let i = 1; i < this.aiSnake2.body.length; i++) {
                if (playerHead.x === this.aiSnake2.body[i].x && playerHead.y === this.aiSnake2.body[i].y) {
                    this.killAISnake(this.aiSnake2);
                    break;
                }
            }
        }
        
        // 检查AI蛇头撞到玩家蛇身
        if (this.aiSnake.isAlive) {
            for (let i = 1; i < this.playerSnake.body.length; i++) {
                if (aiHead.x === this.playerSnake.body[i].x && aiHead.y === this.playerSnake.body[i].y) {
                    this.endGame('AI撞到玩家蛇身！玩家获胜！');
                    return;
                }
            }
        }
        
        if (this.isChallengeMode && this.aiSnake2.isAlive) {
            for (let i = 1; i < this.playerSnake.body.length; i++) {
                if (aiHead2.x === this.playerSnake.body[i].x && aiHead2.y === this.playerSnake.body[i].y) {
                    this.endGame('AI撞到玩家蛇身！玩家获胜！');
                    return;
                }
            }
        }
        
        // 挑战模式下检查AI蛇之间的碰撞（不会相互撞死，但会避免）
        if (this.isChallengeMode && this.aiSnake.isAlive && this.aiSnake2.isAlive) {
            // AI蛇头相撞 - 不会死亡，但会触发AI的避让逻辑
            if (aiHead.x === aiHead2.x && aiHead.y === aiHead2.y) {
                // 触发AI避让逻辑
                this.ai.avoidCollisionMove(aiHead);
                this.ai2.avoidCollisionMove(aiHead2);
            }
            
            // AI蛇头撞到对方蛇身 - 不会死亡
            for (let i = 1; i < this.aiSnake.body.length; i++) {
                if (aiHead2.x === this.aiSnake.body[i].x && aiHead2.y === this.aiSnake.body[i].y) {
                    this.ai2.avoidCollisionMove(aiHead2);
                }
            }
            
            for (let i = 1; i < this.aiSnake2.body.length; i++) {
                if (aiHead.x === this.aiSnake2.body[i].x && aiHead.y === this.aiSnake2.body[i].y) {
                    this.ai.avoidCollisionMove(aiHead);
                }
            }
        }
    }
    
    checkFood() {
        const playerHead = this.playerSnake.body[0];
        const aiHead = this.aiSnake.body[0];
        const aiHead2 = this.aiSnake2.body[0];
        
        // 检查第一个普通食物
        if (this.food && playerHead.x === this.food.x && playerHead.y === this.food.y) {
            this.playerSnake.score += 10;
            this.playerSnake.body.push({...this.playerSnake.body[this.playerSnake.body.length - 1]});
            this.food = null; // 吃掉第一个食物
            this.generateFood(); // 重新生成食物
            this.updateScoreDisplay();
        }
        
        if (this.food && this.aiSnake.isAlive && aiHead.x === this.food.x && aiHead.y === this.food.y) {
            this.aiSnake.score += 10;
            this.aiSnake.body.push({...this.aiSnake.body[this.aiSnake.body.length - 1]});
            this.food = null; // 吃掉第一个食物
            this.generateFood(); // 重新生成食物
            this.updateScoreDisplay();
        }
        
        if (this.isChallengeMode && this.food && this.aiSnake2.isAlive && aiHead2.x === this.food.x && aiHead2.y === this.food.y) {
            this.aiSnake2.score += 10;
            this.aiSnake2.body.push({...this.aiSnake2.body[this.aiSnake2.body.length - 1]});
            this.food = null; // 吃掉第一个食物
            this.generateFood(); // 重新生成食物
            this.updateScoreDisplay();
        }
        
        // 检查第二个普通食物
        if (this.food2 && playerHead.x === this.food2.x && playerHead.y === this.food2.y) {
            this.playerSnake.score += 10;
            this.playerSnake.body.push({...this.playerSnake.body[this.playerSnake.body.length - 1]});
            this.food2 = null;
            this.updateScoreDisplay();
        }
        
        if (this.food2 && this.aiSnake.isAlive && aiHead.x === this.food2.x && aiHead.y === this.food2.y) {
            this.aiSnake.score += 10;
            this.aiSnake.body.push({...this.aiSnake.body[this.aiSnake.body.length - 1]});
            this.food2 = null;
            this.updateScoreDisplay();
        }
        
        if (this.isChallengeMode && this.food2 && this.aiSnake2.isAlive && aiHead2.x === this.food2.x && aiHead2.y === this.food2.y) {
            this.aiSnake2.score += 10;
            this.aiSnake2.body.push({...this.aiSnake2.body[this.aiSnake2.body.length - 1]});
            this.food2 = null;
            this.updateScoreDisplay();
        }
        
        // 检查金色食物
        if (this.goldenFood && playerHead.x === this.goldenFood.x && playerHead.y === this.goldenFood.y) {
            this.playerSnake.score += 30;
            // 金色食物增加3格长度
            for (let i = 0; i < 3; i++) {
                this.playerSnake.body.push({...this.playerSnake.body[this.playerSnake.body.length - 1]});
            }
            this.goldenFood = null;
            this.goldenFoodTimer = 0;
            this.updateScoreDisplay();
        }
        
        if (this.goldenFood && this.aiSnake.isAlive && aiHead.x === this.goldenFood.x && aiHead.y === this.goldenFood.y) {
            this.aiSnake.score += 30;
            // 金色食物增加3格长度
            for (let i = 0; i < 3; i++) {
                this.aiSnake.body.push({...this.aiSnake.body[this.aiSnake.body.length - 1]});
            }
            this.goldenFood = null;
            this.goldenFoodTimer = 0;
            this.updateScoreDisplay();
        }
        
        if (this.isChallengeMode && this.goldenFood && this.aiSnake2.isAlive && aiHead2.x === this.goldenFood.x && aiHead2.y === this.goldenFood.y) {
            this.aiSnake2.score += 30;
            // 金色食物增加3格长度
            for (let i = 0; i < 3; i++) {
                this.aiSnake2.body.push({...this.aiSnake2.body[this.aiSnake2.body.length - 1]});
            }
            this.goldenFood = null;
            this.goldenFoodTimer = 0;
            this.updateScoreDisplay();
        }
        
        // 检查移动食物（仅在中等难度时生效）
        if (this.ai && this.ai.difficulty === 'medium' && this.movingFood) {
            // 玩家吃到移动食物
            if (playerHead.x === this.movingFood.x && playerHead.y === this.movingFood.y) {
                this.playerSnake.score += 50;
                // 移动食物增加5格长度
                for (let i = 0; i < 5; i++) {
                    this.playerSnake.body.push({...this.playerSnake.body[this.playerSnake.body.length - 1]});
                }
                this.movingFood = null;
                this.movingFoodTimer = 0;
                this.updateScoreDisplay();
                return; // 玩家吃到后立即返回，避免后续检查
            }
            
            // AI吃到移动食物
            if (this.aiSnake.isAlive && aiHead.x === this.movingFood.x && aiHead.y === this.movingFood.y) {
                this.aiSnake.score += 50;
                // 移动食物增加5格长度
                for (let i = 0; i < 5; i++) {
                    this.aiSnake.body.push({...this.aiSnake.body[this.aiSnake.body.length - 1]});
                }
                this.movingFood = null;
                this.movingFoodTimer = 0;
                this.updateScoreDisplay();
            }
            
            if (this.isChallengeMode && this.aiSnake2.isAlive && aiHead2.x === this.movingFood.x && aiHead2.y === this.movingFood.y) {
                this.aiSnake2.score += 50;
                // 移动食物增加5格长度
                for (let i = 0; i < 5; i++) {
                    this.aiSnake2.body.push({...this.aiSnake2.body[this.aiSnake2.body.length - 1]});
                }
                this.movingFood = null;
                this.movingFoodTimer = 0;
                this.updateScoreDisplay();
            }
        }
    }
    
    updateScoreDisplay() {
        document.getElementById('player-score').textContent = this.playerSnake.score;
        document.getElementById('ai-score').textContent = this.aiSnake.score;
        
        // 挑战模式下更新第二条AI的得分
        if (this.isChallengeMode) {
            document.getElementById('ai2-score').textContent = this.aiSnake2.score;
        }
    }
    
    updateAIInfoDisplay() {
        // 挑战模式下显示第二条AI信息
        const ai2Info = document.getElementById('ai2-info');
        if (ai2Info) {
            if (this.isChallengeMode) {
                ai2Info.classList.remove('hidden');
            } else {
                ai2Info.classList.add('hidden');
            }
        }
    }
    
    killAISnake(aiSnake) {
        if (aiSnake === this.aiSnake) {
            this.aiSnake.isAlive = false;
            // 玩家获得被杀死的AI蛇的长度加成
            const aiLength = this.aiSnake.body.length;
            for (let i = 0; i < aiLength; i++) {
                this.playerSnake.body.push({...this.playerSnake.body[this.playerSnake.body.length - 1]});
            }
            this.playerSnake.score += aiLength * 5; // 额外奖励分数
        } else if (aiSnake === this.aiSnake2) {
            this.aiSnake2.isAlive = false;
            // 玩家获得被杀死的AI蛇的长度加成
            const aiLength = this.aiSnake2.body.length;
            for (let i = 0; i < aiLength; i++) {
                this.playerSnake.body.push({...this.playerSnake.body[this.playerSnake.body.length - 1]});
            }
            this.playerSnake.score += aiLength * 5; // 额外奖励分数
        }
        
        this.updateScoreDisplay();
    }
    
    checkGameEnd() {
        // 检查时间结束
        if (this.remainingTime <= 0) {
            this.endGame('时间结束！');
            return;
        }
        
        // 检查玩家死亡
        const playerHead = this.playerSnake.body[0];
        if (playerHead.x < 0 || playerHead.x >= this.gridWidth || 
            playerHead.y < 0 || playerHead.y >= this.gridHeight) {
            this.endGame('玩家撞墙！AI获胜！');
            return;
        }
        
        // 检查玩家撞到自己
        for (let i = 1; i < this.playerSnake.body.length; i++) {
            if (playerHead.x === this.playerSnake.body[i].x && playerHead.y === this.playerSnake.body[i].y) {
                this.endGame('玩家撞到自己！AI获胜！');
                return;
            }
        }
        
        // 检查AI全部死亡（两个AI都死了才算玩家赢）
        if (!this.aiSnake.isAlive && (!this.isChallengeMode || !this.aiSnake2.isAlive)) {
            this.endGame('所有AI都被击败！玩家获胜！');
            return;
        }
    }
    
    draw() {
        // 清空画布
        this.ctx.fillStyle = '#000';
        this.ctx.fillRect(0, 0, this.canvasWidth, this.canvasHeight);
        
        // 绘制边界
        this.ctx.strokeStyle = '#333';
        this.ctx.lineWidth = 2;
        this.ctx.strokeRect(0, 0, this.canvasWidth, this.canvasHeight);
        
        // 绘制网格（调试用）
        // this.drawGrid();
        
        // 绘制第一个普通食物
        if (this.food) {
            this.ctx.fillStyle = '#ff6b6b';
            this.ctx.fillRect(
                this.food.x * this.gridSize,
                this.food.y * this.gridSize,
                this.gridSize,
                this.gridSize
            );
        }
        
        // 绘制第二个普通食物
        if (this.food2) {
            this.ctx.fillStyle = '#ff6b6b';
            this.ctx.fillRect(
                this.food2.x * this.gridSize,
                this.food2.y * this.gridSize,
                this.gridSize,
                this.gridSize
            );
        }
        
        // 绘制金色食物
        if (this.goldenFood) {
            // 金色食物有闪烁效果
            const blink = Math.floor(Date.now() / 200) % 2 === 0;
            this.ctx.fillStyle = blink ? '#ffd700' : '#ffed4e';
            this.ctx.fillRect(
                this.goldenFood.x * this.gridSize,
                this.goldenFood.y * this.gridSize,
                this.gridSize,
                this.gridSize
            );
            
            // 金色边框
            this.ctx.strokeStyle = '#ff9800';
            this.ctx.lineWidth = 2;
            this.ctx.strokeRect(
                this.goldenFood.x * this.gridSize,
                this.goldenFood.y * this.gridSize,
                this.gridSize,
                this.gridSize
            );
        }
        
        // 绘制移动食物（仅在中等难度时生效）
        if (this.ai && this.ai.difficulty === 'medium' && this.movingFood) {
            // 移动食物有旋转效果
            const rotation = Math.floor(Date.now() / 100) % 4;
            this.ctx.save();
            this.ctx.translate(
                this.movingFood.x * this.gridSize + this.gridSize / 2,
                this.movingFood.y * this.gridSize + this.gridSize / 2
            );
            this.ctx.rotate(rotation * Math.PI / 2);
            
            // 移动食物主体（紫色）
            this.ctx.fillStyle = '#9c27b0';
            this.ctx.fillRect(-this.gridSize / 2, -this.gridSize / 2, this.gridSize, this.gridSize);
            
            // 移动食物边框（深紫色）
            this.ctx.strokeStyle = '#6a1b9a';
            this.ctx.lineWidth = 2;
            this.ctx.strokeRect(-this.gridSize / 2, -this.gridSize / 2, this.gridSize, this.gridSize);
            
            // 移动食物内部装饰（白色十字）
            this.ctx.strokeStyle = '#ffffff';
            this.ctx.lineWidth = 1;
            this.ctx.beginPath();
            this.ctx.moveTo(-this.gridSize / 4, 0);
            this.ctx.lineTo(this.gridSize / 4, 0);
            this.ctx.moveTo(0, -this.gridSize / 4);
            this.ctx.lineTo(0, this.gridSize / 4);
            this.ctx.stroke();
            
            this.ctx.restore();
        }
        
        // 绘制玩家蛇
        this.drawSnake(this.playerSnake);
        
        // 绘制AI蛇
        if (this.aiSnake.isAlive) {
            this.drawSnake(this.aiSnake);
        }
        
        // 挑战模式下绘制第二条AI蛇
        if (this.isChallengeMode && this.aiSnake2.isAlive) {
            this.drawSnake(this.aiSnake2);
        }
    }
    
    drawGrid() {
        this.ctx.strokeStyle = '#222';
        this.ctx.lineWidth = 0.5;
        
        for (let x = 0; x <= this.canvasWidth; x += this.gridSize) {
            this.ctx.beginPath();
            this.ctx.moveTo(x, 0);
            this.ctx.lineTo(x, this.canvasHeight);
            this.ctx.stroke();
        }
        
        for (let y = 0; y <= this.canvasHeight; y += this.gridSize) {
            this.ctx.beginPath();
            this.ctx.moveTo(0, y);
            this.ctx.lineTo(this.canvasWidth, y);
            this.ctx.stroke();
        }
    }
    
    drawSnake(snake) {
        // 绘制蛇身
        for (let i = 0; i < snake.body.length; i++) {
            const segment = snake.body[i];
            
            if (i === 0) {
                // 蛇头 - 添加特殊效果
                this.ctx.fillStyle = snake.headColor;
                this.ctx.fillRect(
                    segment.x * this.gridSize,
                    segment.y * this.gridSize,
                    this.gridSize,
                    this.gridSize
                );
                
                // 蛇头特殊效果：眼睛和装饰
                this.ctx.fillStyle = '#FFFFFF';
                
                // 根据蛇的类型添加不同的特殊效果
                if (snake === this.playerSnake) {
                    // 玩家蛇头：绿色眼睛
                    this.ctx.fillStyle = '#2E7D32';
                    this.ctx.fillRect(
                        segment.x * this.gridSize + 4,
                        segment.y * this.gridSize + 4,
                        4, 4
                    );
                    this.ctx.fillRect(
                        segment.x * this.gridSize + this.gridSize - 8,
                        segment.y * this.gridSize + 4,
                        4, 4
                    );
                } else if (snake === this.aiSnake) {
                    // 橙色AI蛇头：橙色火焰效果
                    this.ctx.fillStyle = '#FF5722';
                    this.ctx.fillRect(
                        segment.x * this.gridSize + 3,
                        segment.y * this.gridSize + 3,
                        3, 3
                    );
                    this.ctx.fillRect(
                        segment.x * this.gridSize + this.gridSize - 6,
                        segment.y * this.gridSize + 3,
                        3, 3
                    );
                    // 火焰装饰
                    this.ctx.fillStyle = '#FF9800';
                    this.ctx.fillRect(
                        segment.x * this.gridSize + 6,
                        segment.y * this.gridSize + 2,
                        2, 2
                    );
                } else if (snake === this.aiSnake2) {
                    // 红色AI蛇头：红色菱形效果
                    this.ctx.fillStyle = '#F44336';
                    this.ctx.fillRect(
                        segment.x * this.gridSize + 4,
                        segment.y * this.gridSize + 4,
                        3, 3
                    );
                    this.ctx.fillRect(
                        segment.x * this.gridSize + this.gridSize - 7,
                        segment.y * this.gridSize + 4,
                        3, 3
                    );
                    // 菱形装饰
                    this.ctx.fillStyle = '#D32F2F';
                    this.ctx.fillRect(
                        segment.x * this.gridSize + 7,
                        segment.y * this.gridSize + 7,
                        2, 2
                    );
                }
            } else {
                // 蛇身
                this.ctx.fillStyle = snake.color;
                this.ctx.fillRect(
                    segment.x * this.gridSize,
                    segment.y * this.gridSize,
                    this.gridSize,
                    this.gridSize
                );
            }
            
            // 蛇身边框
            this.ctx.strokeStyle = '#000';
            this.ctx.lineWidth = 1;
            this.ctx.strokeRect(
                segment.x * this.gridSize,
                segment.y * this.gridSize,
                this.gridSize,
                this.gridSize
            );
        }
    }
    
    togglePause() {
        if (!this.gameRunning || this.gameOver) return;
        
        this.gamePaused = !this.gamePaused;
        const pauseBtn = document.getElementById('pauseBtn');
        
        if (this.gamePaused) {
            pauseBtn.innerHTML = '<i class="bi bi-play-fill"></i> 继续';
            pauseBtn.classList.remove('btn-warning');
            pauseBtn.classList.add('btn-success');
        } else {
            pauseBtn.innerHTML = '<i class="bi bi-pause-fill"></i> 暂停';
            pauseBtn.classList.remove('btn-success');
            pauseBtn.classList.add('btn-warning');
            this.gameLoop();
        }
    }
    
    endGame(message) {
        this.gameRunning = false;
        this.gameOver = true;
        
        clearInterval(this.timerInterval);
        
        // 显示结果
        this.showGameResult(message);
    }
    
    showGameResult(message) {
        const result = document.getElementById('gameResult');
        const title = document.getElementById('resultTitle');
        const playerScore = document.getElementById('finalPlayerScore');
        const aiScore = document.getElementById('finalAiScore');
        const ai2Score = document.getElementById('finalAi2Score');
        const ai2ScoreStat = document.getElementById('finalAi2ScoreStat');
        const duration = document.getElementById('gameDuration');
        
        title.textContent = message;
        playerScore.textContent = this.playerSnake.score;
        aiScore.textContent = this.aiSnake.score;
        
        // 挑战模式下显示第二条AI的得分
        if (this.isChallengeMode && ai2Score && ai2ScoreStat) {
            ai2Score.textContent = this.aiSnake2.score;
            ai2ScoreStat.classList.remove('hidden');
        } else if (ai2ScoreStat) {
            ai2ScoreStat.classList.add('hidden');
        }
        
        const playedTime = (this.isChallengeMode ? this.challengeTotalTime : this.totalTime) - this.remainingTime;
        const minutes = Math.floor(playedTime / 60);
        const seconds = playedTime % 60;
        duration.textContent = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
        
        result.classList.remove('hidden');
    }
    
    restartGame() {
        this.gameRunning = false;
        this.gamePaused = false;
        this.gameOver = false;
        this.gameStarted = false;
        
        clearInterval(this.timerInterval);
        
        document.getElementById('gameResult').classList.add('hidden');
        
        this.resetGame();
        this.showStartScreen();
        
        // 重置暂停按钮
        const pauseBtn = document.getElementById('pauseBtn');
        pauseBtn.innerHTML = '<i class="bi bi-pause-fill"></i> 暂停';
        pauseBtn.classList.remove('btn-success');
        pauseBtn.classList.add('btn-warning');
    }
}

// 页面加载完成后初始化游戏
document.addEventListener('DOMContentLoaded', () => {
    new LocalPVEGame();
});